const Engine = Matter.Engine
const Render = Matter.Render
const Bodies = Matter.Bodies
const Composite = Matter.Composite
const Composites = Matter.Composites
const Constraint = Matter.Constraint
const Runner = Matter.Runner
const [width, height] = [(window.innerWidth - 4), (window.innerHeight - 4)]
 // 3. 创建引擎
let engine = Engine.create()
let render;
let runner;
function initMatter(name){
        // 4. 创建渲染器，并将引擎连接到画布上
        render = Render.create({
            element: document.getElementById(name), // 绑定页面元素
            engine: engine, // 绑定引擎
            options: {//设置
                wireframes: false,//关闭边框线，改为填充色
                width: width,
                height: height
            }
        })
        // 7. 执行渲染操作
        Render.run(render)
        // 8. 创建运行方法
        runner = Runner.create();
        // 9. 运行渲染器
        Runner.run(runner, engine)
}
function addWall(){
    let [x,y,s,wall]=[width/2,height/2,10,null]
    for(let i=0;i<4;i++){
        if(i==0){
            wall=bodyRect(x,0,width,s,true);
        }else if(i==1){
            wall=bodyRect(x,height,width,s,true);
        }else if(i==2){
            wall=bodyRect(0,y,s,height,true);
        }else if(i==3){
            wall=bodyRect(width,y,s,height,true);
        }
        addBody(wall)
    }
}
function addBody(...arg){
    Matter.Composite.add(engine.world,arg)
}
/**方形*/
function bodyRect(x,y,w,h,isStatic=false,angle=0){
    let rect=Bodies.rectangle(x,y,w,h,{isStatic:isStatic,angle:angle})
    if(isStatic){
        rect.render.fillStyle='#666'
    }
    return rect;
}
/**圆形*/
function bodyCircle(x,y,r){
    return Bodies.circle(x,y,r);
}
/**多边形，n为边数，r为半径*/
function bodyPolygon(x,y,n,r){
    return Bodies.polygon(x, y, n, r)
}
/**梯形,s为斜率0到1之间，小于0倒过来的梯形，等于0为矩形，大于等于1为三角形*/
function bodyTrapezoid(x,y,w,h,s){
    return Bodies.trapezoid(x, y, w, h, s)
}
/**创建多个刚体,x,y为位置，xnum,ynum为x轴和y轴数量，xoff,yoff为间距，w,h为宽高（w也为圆半径）,t为类型 */
function stack(x,y,xnum,ynum,xoff,yoff,w,h,t='rect'){
    return Composites.stack(x,y,xnum,ynum,xoff,yoff, function (x, y) {
        if(t=='circle')return Matter.Bodies.circle(x, y, w)
        else if(t=='rect')return Matter.Bodies.rectangle(x, y, w, h)
    })
}
/***鼠标拖动*/
function mousrDrag(){
    // 创建鼠标实例
    let mouse = Matter.Mouse.create(render.canvas)
    // 给鼠标添加约束
    let mouseConstraint = Matter.MouseConstraint.create(engine, {
        mouse: mouse,
        constraint: {
            stiffness: 0.2,
            render: {
                visible: true // 默认为 true，会显示鼠标拖拽轨迹
            }
        }
    })
    addBody(mouseConstraint);
    return mouseConstraint;
}
function toAngle(a){
    return Math.PI*a/180;
}

